// +----------------------------------------------------------------------
// | Manong.Cloud [ 领酷码农云 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2020 http://www.manong.cloud All rights reserved.
// +----------------------------------------------------------------------
// | Author: 稻草人 <qinuoyun@qq.com>
// +----------------------------------------------------------------------
// | Member: 围棋 飘逸者 Loumt Silence24
// +----------------------------------------------------------------------
import WebSocket from "ws";

// 字符串下划线转驼峰
function toHump(name) {
  function getName(name) {
    return name.replace(/\_(\w)/g, function (all, letter) {
      return letter.toUpperCase();
    });
  }

  name = getName(name);
  return name.replace(/\-(\w)/g, function (all, letter) {
    return letter.toUpperCase();
  });
}

export default class websocket {
  static online = 0 // 在线连接
  static ws = WebSocket.Server //默认实例

  // 发送客户端数据
  static sendToCliect(Data) {
    let iskeep = false // 加个变量做下发成功判断
    if (!(this.ws instanceof WebSocket.Server)) {
      return iskeep;
    }
    const {id} = Data
    this.ws.clients.forEach((client) => {
      if (client.readyState === WebSocket.OPEN && client.id === id) {
        // 发送给指定匹配id
        client.send(JSON.stringify(Data));
        iskeep = true
      }
    });
    return iskeep;
  }


  static init(server, component) {
    // 创建实例
    this.ws = new WebSocket.Server({server, path: '/websocket'});
    let socketClass = new component(this.ws);
    this.ws.on('connection', async (ws, request) => {
        let returned = null;
        if (!(request.url.includes('/websocket'))) {
          return ws.close();
        }
        this.online = this.ws._server._connections;
        console.log(`socket当前在线${this.online}个连接`)

        ws.on('message', (message) => {
          //console.log('【消息】message: %s', message);
          try {
            let data = JSON.parse(message);
            //获取回调模式
            if (data && data.retcode === 0) {
              //读取控制器信息
              returned = new Promise(async (resolve, reject) => {
                try {
                  console.log("此处处理回调信息")
                  resolve(await socketClass['__callback'](ws, data));
                } catch (error) {
                  console.log('【消息】错误消息: %s', message);
                  reject(error)
                }
              });
            }
            if (data && data.retcode > 0) {
              console.log('【反馈】错误编码: %s', data);
            }
            //获取事件模式
            if (data && data.action) {
              //格式化名称
              let name = toHump(data.action);
              //获取名称
              let action = name.charAt(0).toUpperCase() + name.slice(1);
              //重置名称
              action = 'action' + action;
              //读取控制器信息
              returned = new Promise(async (resolve, reject) => {
                try {
                  resolve(await socketClass[action](ws, data));
                } catch (error) {
                  console.log('【消息】message: %s', message);
                  reject(error)
                }
              });
            }
            //设置返回ID
            let reqid = new Date().getTime();
            if (data && data.header && data.header.reqid) {
              reqid = data.header.reqid
            }
            if (returned) {
              //执行返回数据
              returned.then(body => {
                let object = {
                  "retcode": 0,
                  "header": {
                    "reqid": reqid
                  }
                }
                if (body) {
                  object['body'] = body;
                }
                ws.send(JSON.stringify(object))
              }).catch(error => {
                console.log("错误信息", reqid, error)
              })
            }
          } catch (error) {
            console.log("访问错误信息", error)
          }
        });
      }
    )
  }
}
